const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreDisplay = document.getElementById('score');
const difficultySelect = document.getElementById('difficulty');
const restartButton = document.getElementById('restartButton');

canvas.width = 1200;
canvas.height = 800;

// Difficulty settings
const difficultySettings = {
    easy: {
        playerSpeed: 7,
        fishMinSpeed: 0.5,
        fishMaxSpeed: 2.5,
        spawnRate: 90, // Higher number means less frequent spawns
        playerGrowthFactor: 0.2 // Faster growth
    },
    medium: {
        playerSpeed: 5,
        fishMinSpeed: 1.0,
        fishMaxSpeed: 3.5,
        spawnRate: 60,
        playerGrowthFactor: 0.1 // Normal growth
    },
    hell: {
        playerSpeed: 4,
        fishMinSpeed: 2.0,
        fishMaxSpeed: 5.0,
        spawnRate: 30, // Lower number means more frequent spawns
        playerGrowthFactor: 0.05 // Slower growth
    }
};

let currentDifficulty = 'medium'; // Default difficulty

let targetX = -1;
let targetY = -1;

let gameRunning = false;
let score = 0;
let playerFish;
let allFish = []; // Will hold all other fish (small, medium, large)
import { PIXEL_ART_FISH, drawPixelArt } from './assets/fish_pixel_art.js';

let frame = 0; // For controlling fish spawning
// Player Fish
class PlayerFish {
    constructor() {
        this.size = 50;
        this.x = canvas.width / 4;
        this.y = canvas.height / 2;
        this.speed = difficultySettings[currentDifficulty].playerSpeed;
        this.dx = 0;
        this.dy = 0;
        // this.color = 'yellow'; // Color now comes from pixel art data
        this.direction = 'right';
        this.isEating = false; // Keep for collision/growth logic
        this.mouthOpen = false; // For drawing animation
        this.mouthAnimationTimer = 0;
        this.mouthAnimationDuration = 15; // frames
        this.fishData = PIXEL_ART_FISH[0]; // Player fish uses the first pixel art fish
    }

    draw() {
        drawPixelArt(ctx, this.fishData, this.x, this.y, this.size, this.direction, this.mouthOpen);
    }

    update() {
        if (targetX !== -1 && targetY !== -1) { // Only move if a target is set
            const dirX = targetX - (this.x + this.size / 2);
            const dirY = targetY - (this.y + this.size / 2);

            const magnitude = Math.sqrt(dirX * dirX + dirY * dirY);
            const threshold = 5; // Stop if within 5 pixels of target

            if (magnitude > threshold) {
                this.dx = (dirX / magnitude) * this.speed;
                this.dy = (dirY / magnitude) * this.speed;
            } else {
                this.dx = 0;
                this.dy = 0;
            }
        } else { // If no target (e.g., mouse not yet moved over canvas)
            this.dx = 0;
            this.dy = 0;
        }

        if (this.dx > 0) {
            this.direction = 'right';
        } else if (this.dx < 0) {
            this.direction = 'left';
        }

        this.x += this.dx;
        this.y += this.dy;

        if (this.x < 0) this.x = 0;
        if (this.x + this.size > canvas.width) this.x = canvas.width - this.size;
        if (this.y < 0) this.y = 0;
        if (this.y + this.size > canvas.height) this.y = canvas.height - this.size;

        // Player mouth animation
        if (this.isEating) {
            this.mouthAnimationTimer++;
            if (this.mouthAnimationTimer < this.mouthAnimationDuration / 2) {
                this.mouthOpen = true;
            } else {
                this.mouthOpen = false;
            }
            if (this.mouthAnimationTimer >= this.mouthAnimationDuration) {
                this.isEating = false;
                this.mouthAnimationTimer = 0;
                this.mouthOpen = false;
            }
        }
    }
}

// Generic Fish (Small, Medium, Large)
class Fish {
    constructor(type, fishId) {
        this.type = type; // 'smallFish', 'mediumFish', 'largeFish'
        this.fishId = fishId; // Unique ID for drawing variations (0-29)
        this.x = canvas.width; // Start off-screen right
        this.y = Math.random() * (canvas.height - 50);
        this.speed = Math.random() * (difficultySettings[currentDifficulty].fishMaxSpeed - difficultySettings[currentDifficulty].fishMinSpeed) + difficultySettings[currentDifficulty].fishMinSpeed;
        // this.color = this.getFishColor(fishId); // Color now comes from pixel art data
        this.mouthOpen = false;
        this.mouthAnimationTimer = 0;
        this.mouthAnimationDuration = 10;
        this.direction = 'left';
        this.fishData = PIXEL_ART_FISH[this.fishId % PIXEL_ART_FISH.length]; // Assign pixel art data

        if (this.type === 'smallFish') {
            this.size = (20 + Math.random() * 10) * this.fishData.sizeFactor;
            this.speed = Math.random() * (difficultySettings[currentDifficulty].fishMaxSpeed * 1.2 - difficultySettings[currentDifficulty].fishMinSpeed * 1.2) + difficultySettings[currentDifficulty].fishMinSpeed * 1.2;
        } else if (this.type === 'mediumFish') {
            this.size = (40 + Math.random() * 15) * this.fishData.sizeFactor;
            this.speed = Math.random() * (difficultySettings[currentDifficulty].fishMaxSpeed - difficultySettings[currentDifficulty].fishMinSpeed) + difficultySettings[currentDifficulty].fishMinSpeed;
        } else if (this.type === 'largeFish') {
            this.size = (70 + Math.random() * 30) * this.fishData.sizeFactor;
            this.speed = Math.random() * (difficultySettings[currentDifficulty].fishMaxSpeed * 0.5 - difficultySettings[currentDifficulty].fishMinSpeed * 0.5) + difficultySettings[currentDifficulty].fishMinSpeed * 0.5;
        }
        this.growthFactor = 1;
    }

    // getFishColor(id) { // No longer needed
    //     const colors = [
    //         '#FF6347', '#FFD700', '#ADFF2F', '#6495ED', '#BA55D3', '#FF4500', '#00FFFF', '#FF69B4', '#7B68EE', '#3CB371',
    //         '#FF8C00', '#8A2BE2', '#00CED1', '#F08080', '#20B2AA', '#DA70D6', '#B0C4DE', '#9ACD32', '#FF1493', '#4682B4',
    //         '#D2691E', '#9370DB', '#00FA9A', '#8B0000', '#483D8B', '#DEB887', '#7FFF00', '#DC143C', '#00BFFF', '#8B008B'
    //     ];
    //     return colors[id % colors.length];
    // }

    draw() {
        // Draw pixel art
        drawPixelArt(ctx, this.fishData, this.x, this.y, this.size * this.growthFactor, this.direction, this.mouthOpen);
    }

    update() {
        this.x -= this.speed;
    }
}

async function initGame() {
    gameRunning = true;
    score = 0;
    scoreDisplay.textContent = `Score: ${score}`;
    allFish = [];
    frame = 0;
    restartButton.style.display = 'none';

    // Apply difficulty settings
    currentDifficulty = difficultySelect.value;
    playerFish = new PlayerFish(); // Re-initialize player fish to apply new speed
    gameLoop();
}

function gameLoop() {
    if (!gameRunning) return;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    playerFish.update();
    playerFish.draw();

    // No need for player mouth animation logic here anymore, it's in PlayerFish.update()

    // Spawn fish
    if (frame % difficultySettings[currentDifficulty].spawnRate === 0) {
        const rand = Math.random();
        const newFishId = Math.floor(Math.random() * 30); // Random ID for 30 varieties
        if (rand < 0.6) { // 60% small fish
            allFish.push(new Fish('smallFish', newFishId));
        } else if (rand < 0.9) { // 30% medium fish
            allFish.push(new Fish('mediumFish', newFishId));
        } else { // 10% large fish
            allFish.push(new Fish('largeFish', newFishId));
        }
    }

    // Update and draw all fish
    for (let i = 0; i < allFish.length; i++) {
        const currentFish = allFish[i];
        currentFish.update();
        currentFish.draw();

        // Trigger mouth animation for large fish when player is close
        if (currentFish.type === 'largeFish') {
            const distanceX = Math.abs((playerFish.x + playerFish.size / 2) - (currentFish.x + currentFish.size * currentFish.growthFactor / 2));
            const distanceY = Math.abs((playerFish.y + playerFish.size / 2) - (currentFish.y + currentFish.size * currentFish.growthFactor / 2));
            const triggerDistance = (playerFish.size + currentFish.size * currentFish.growthFactor) / 2 + 30; // 30 pixels buffer

            if (distanceX < triggerDistance && distanceY < triggerDistance) {
                currentFish.mouthOpen = true;
            } else {
                currentFish.mouthOpen = false; // Close mouth if player moves away
            }
        }


        // Mouth animation for large fish (prey)
        if (currentFish.type === 'largeFish' && currentFish.mouthOpen) {
            currentFish.mouthAnimationTimer++;
            if (currentFish.mouthAnimationTimer >= currentFish.mouthAnimationDuration) {
                currentFish.mouthOpen = false;
                currentFish.mouthAnimationTimer = 0;
            }
        }

        // Collision detection
        // Adjust collision check to use the current scaled size
        const playerScaledSize = playerFish.size;
        const currentFishScaledSize = currentFish.size * currentFish.growthFactor;

        // Introduce a small buffer for player collision
        const collisionBuffer = 5; // pixels
        const playerCollisionRect = {
            x: playerFish.x - collisionBuffer,
            y: playerFish.y - collisionBuffer,
            size: playerScaledSize + collisionBuffer * 2
        };

        if (checkCollision(playerCollisionRect, { x: currentFish.x, y: currentFish.y, size: currentFishScaledSize })) {
            // Player eats fish
            if (playerScaledSize >= currentFishScaledSize) { // Changed from > to >= for sensitivity
                score += 10;
                scoreDisplay.textContent = `Score: ${score}`;
                playerFish.size = Math.min(playerFish.size + currentFish.size * difficultySettings[currentDifficulty].playerGrowthFactor, canvas.width / 4); // Player grows, adjusted by difficulty
                playerFish.isEating = true;
                playerFish.mouthAnimationTimer = 0;
                allFish.splice(i, 1); // Remove eaten fish
                i--; // Adjust index after removal
            } else { // Fish eats player
                gameOver();
                return; // Stop the loop
            }
        }
        // Remove off-screen fish
        if (allFish[i] && allFish[i].x + allFish[i].size * allFish[i].growthFactor < 0) {
            allFish.splice(i, 1);
            i--;
        }
    }

    frame++;
    requestAnimationFrame(gameLoop);
}

// Simple AABB collision detection
function checkCollision(rect1, rect2) {
    return rect1.x < rect2.x + rect2.size &&
           rect1.x + rect1.size > rect2.x &&
           rect1.y < rect2.y + rect2.size &&
           rect1.y + rect2.size > rect2.y;
}

function gameOver() {
    gameRunning = false;
    ctx.font = '50px Arial';
    ctx.fillStyle = 'red';
    ctx.textAlign = 'center';
    ctx.fillText('Game Over!', canvas.width / 2, canvas.height / 2 - 30);
    ctx.fillText(`Final Score: ${score}`, canvas.width / 2, canvas.height / 2 + 30);
    restartButton.style.display = 'block';
}

// --- Input Handlers ---

// Mouse/Touch controls
canvas.addEventListener('mousemove', (e) => {
    if (gameRunning) {
        updatePlayerDirection(e);
    }
});

// canvas.addEventListener('mouseleave', () => {
//     if (playerFish) { // Ensure playerFish exists before trying to access it
//         playerFish.dx = 0;
//         playerFish.dy = 0;
//     }
// });

canvas.addEventListener('touchstart', (e) => {
    e.preventDefault(); // Prevent scrolling
    if (gameRunning) {
        updatePlayerDirection(e.touches[0]);
    }
});
canvas.addEventListener('touchmove', (e) => {
    e.preventDefault(); // Prevent scrolling
    if (gameRunning) {
        updatePlayerDirection(e.touches[0]);
    }
});
// canvas.addEventListener('touchend', () => {
//     if (playerFish) { // Ensure playerFish exists before trying to access it
//         playerFish.dx = 0;
//         playerFish.dy = 0;
//     }
// });

function updatePlayerDirection(event) {
    if (!gameRunning) return;
    const rect = canvas.getBoundingClientRect();
    targetX = event.clientX - rect.left;
    targetY = event.clientY - rect.top;

    // No need to set playerFish.dx/dy here, it will be done in PlayerFish.update()
}


// Restart button
restartButton.addEventListener('click', initGame);

// Difficulty change listener
difficultySelect.addEventListener('change', initGame); // Restart game on difficulty change

// Start the game
initGame();
